package com.demo.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

//netty server
@Slf4j
public class HelloWorldDemo {

    public static void main(String[] args) throws InterruptedException {
        createServerV2();
//        createClient();
    }

    private static void createServer() {
        //1.创建一个server
        new ServerBootstrap()
                //2.选择loop组
                //第一个nioeventloopgroup 作为boss， 只处理accept 事件, 默认只会有一个线程池
                //第二个nioeventloopgroup(2) 作为worker， 处理socketchannel上的 read write
                .group(new NioEventLoopGroup())
                //3.选择 serversocketchannel 实现, 可以accept read
                //16. 由某个eventloop read 数据
                .channel(NioServerSocketChannel.class)
                //4.添加handler
                .childHandler(
                        //5.添加初始化器， 当accept时才会执行
                        new ChannelInitializer<NioSocketChannel>() {
                            //12. 连接建立，调用初始化方法
                            @Override
                            protected void initChannel(NioSocketChannel ch) throws Exception {
                                //17. decode 数据
                                ch.pipeline().addLast(new StringDecoder());     //编码
                                //18. 按顺序执行
                                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {  //读事件
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        System.out.println(msg);
                                    }
                                });
                            }
                        })
                //6.绑定监听端口
                .bind(8080);
    }

    private static void createClient() throws InterruptedException {
        //7. 创建启动类
        new Bootstrap()
                // 8.添加eventloop
                .group(new NioEventLoopGroup())
                //9.选择channel实现
                .channel(NioSocketChannel.class)
                //10.此处只是添加处理器， 连接成功时才会调用
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    //建立连接之后被调用
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        //15. encode 数据
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                //11.连接服务器
                .connect(new InetSocketAddress("localhost", 8080))
                //13.阻塞方法，连接建立后才会使用
                .sync()
                //此处获取了连接对象channel
                .channel()
                //14.发送数据
                .writeAndFlush("hello world");
    }

    private static void createServerV2() throws InterruptedException {
        //独立的eventloopgroup 处理与IO无关的任务
        DefaultEventLoopGroup defaultEventLoopGroup = new DefaultEventLoopGroup();
        new ServerBootstrap()
                .group(
                        //boss 只负责serversocketchannel 的accept事件， 不用指定线程
                        new NioEventLoopGroup(),
                        //worker 负责socketchannel 上的 read write，指定2个线程
                        new NioEventLoopGroup(2)
                )
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {

                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast("handler1", new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf = (ByteBuf) msg;
//                                System.out.println(byteBuf.toString(Charset.defaultCharset()));
                                log.info(byteBuf.toString(Charset.defaultCharset()));
                                // 使用自定义的 handleradapter 时，需要使用此方法，将msg传递给下一个handler
                                ctx.fireChannelRead(msg);
                            }
                        }).addLast(defaultEventLoopGroup, "handler2", new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf = (ByteBuf) msg;
//                                System.out.println(byteBuf.toString(Charset.defaultCharset()));
                                log.info(byteBuf.toString(Charset.defaultCharset()));
                                // 使用自定义的 handleradapter 时，需要使用此方法，将msg传递给下一个handler
                            }
                        });
                    }
                })
                .bind(8080);
    }

}
